const util = require('../../../../../utils/util');
const request = require('../../../../../utils/request')
const common = require('../../../../../utils/common');
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        navbarHeight: 0,
        scrollTop: 0,
        status: 1,

        isShowReason: false, //取消订单原因
        isShowPayType: false, //支付方式选择
        showPay: false, //输入支付密码
        list: [],


        isconfim: '', //是否是确认订单跳转，则直接返回订单列表
        order_id: '',
        detailInfo: {},
        orderInfo: {},
        address: null,
        discount: {},
        goods: [],
        remain_time: '', //剩余支付时间

        hour: '',
        minute: '',
        second: '',
        userInfo:{},

        isShowNum:2,//展示更多

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            navbarHeight: util.getNavbarHeight(),
            order_id: options.id
        })
        //改变头部电量条背景色
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#ffffff',
        })
        this.setData({
            isconfim: options.isconfim
        })
    },
    onShow() {
        this.getYouLike()
        // this.changeGetAdd()
        this.getDetail()
        this.getUserInfo()
    },
    getUserInfo() {
        let _this = this
        request._get('/api?method=user.info', {}, 'noload').then(res => {
            _this.setData({
                userInfo:res.data
            })
        }).catch((res) => {
        })
    },
    // 返回前一 页
    backDealt() {
        if (this.data.isconfim) {
            wx.reLaunch({
                url: '/pages/mine/pages/my/all-orders/all-orders',
            });
        } else {
            wx.navigateBack({
                delta: 1, // 回退前 delta(默认为1) 页面
            })
        }
    },
    // 滑动头部动画
    onPageScroll(e) {
        this.setData({
            scrollTop: e.scrollTop,
        });
    },
    // 关弹框
    closeReason() {
        this.setData({
            isShowReason: false,
            isShowPayType: false
        })
    },
    // 猜你喜欢
    getYouLike() {
        let _this = this
        request._post('/api?method=goods.goodslist', {
            xiaoqu: wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
        }).then(res => {
            _this.setData({
                list: res.data
            })
        })
    },
    // 猜你喜欢-详情
    toDetail(e) {
        wx.navigateTo({
            url: '/pages/home/pages/my/product-details/product-details?id=' + e.currentTarget.dataset.item.goods_id,
        })
    },
    // 获取详情
    getDetail() {
        let _this = this
        request._post('/api?method=order.orderInfo', {
            order_id: this.data.order_id
        }).then(res => {
            _this.setData({
                detailInfo: res.data,
                address: res.data.address,
                complate_pic: res.data.complate_pic ? res.data.complate_pic.split(',') : [],
                // 'address.mobile': common.hideFourNum(res.data.address.mobile),
                goods: res.data.items,
                orderInfo: res.data,
                // 'orderInfo.ctime': res.data.order_info.ctime,
                // discount: res.data.discount,
                // 'discount.order_amount': Number(res.data.discount.order_amount),
                // 'discount.cost_freight': Number(res.data.discount.cost_freight),
            })
            console.log(_this.data.complate_pic,45)
            if (res.data.pay_due_time) {
                _this.countDown(res.data.pay_due_time)
            }
        })
    },
    // 复制
    copy(e) {
        let _this = this
        app.copyInfo(e)
    },
    previewImg(e){
      var that = this
      var current = e.target.dataset.imgurl; // 获取当前点击的图片URL  
      wx.previewImage({  
        current: current, // 当前显示图片的http链接  
        urls: that.data.complate_pic // 需要预览的图片http链接列表  
      }); 
    },
    // 倒计时
    countDown(endTime) {
        if (!endTime) {
            return
        }
        let timer = setInterval(() => {
            //截止时间
            var obj = {}
            let time = endTime
            time--;
            let now = new Date().getTime();
            let diff = parseInt(time - now / 1000);
            
            if (diff < 0) {
                clearInterval(timer)
                this.setData({
                    isCountDown: false
                })
            } else {
                let date = common.formattime(diff * 1000);
                this.setData({
                    hour: date.hour,
                    minute: date.minute,
                    second: date.second
                })
               

            }

        }, 1000)
        this.setData({
            timer
        })
    },
    add(e) {
      let list = this.data.list
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      if (!item.addSwitch) {
        item.addSwitch = true
        item.cart_num++
      }
      this.addCartApi(item,index)
      list[index] = item
      this.setData({
        list
      })
    },
    // 购物车加减
    addCartReduce(e) {
      let type = e.detail.type ? e.detail.type : e.currentTarget.dataset.type //1 减 2 加
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      let list = this.data.list
      if (type == 1) {
        if (item.cart_num == 0) {
          // getApp().toast('商品不能再减了~')
          return
        }
        item.cart_num--
      } else {
        item.cart_num++
      }
  
      this.addCartApi(item, index)
      list[index] = Object.assign(list[index], item)
      this.setData({
        list
      })
  
    },
    addCartApi(item, index) {
      let list = this.data.list
      request._post('/api?method=cart.add', {
        product_id: item.product_id,
        nums: item.cart_num,
        num_type: 2,
      }, 'noload').then(res => {
        getApp().getCartNum()
        getApp().globalData.changePoint = true
        if(item.cart_num == 0){
          list[index].addSwitch = false
          this.setData({
            [`list[${index}]`]: list[index]
          })
        }
      }).catch(res => {
        // 库存不足情况--
        list[index].cart_num--
        if( list[index].cart_num == 0) {
          list[index].addSwitch =false
        }
        this.setData({
          [`list[${index}]`]: list[index]
        })
      })
    },
    // 按钮操作
    handelButton(e) {
        let type = e.currentTarget.dataset.type
        if (type == 1) {
            this.setData({
                isShowReason: true
            })
        } else if (type == 2) { // 删除订单
            this.delOrderApi()
        } else if (type == 3) { // 提醒发货
            this.remindSend()
        } else if (type == 4) { //延长收货
            this.lengthenOrder()
        } else if (type == -1) { //支付
            this.payApi()
            // this.setData({
            //     isShowPayType: true
            // })
        } else if (type == 6) { //申请售后
          this.applyShouhou()
        }else if (type == 7) { //确认收货
            this.sureGetOrder()
        } else if (type == 5) { //再次购买
            let orderInfo = this.data.detailInfo.order_info
            request._post('/api?method=order.buyagain', {
              order_id:orderInfo.order_id
            }, 'noload').then(res => {
                getApp().globalData.rebuyIds = res.data
                setTimeout(function() {
                    wx.switchTab({
                        url:'/pages/shoppingCart/shoppingCart'
                    })
                },1000)
			})
        }

    },
     // 申请售后
     applyShouhou() {
        let _this = this
        wx.showModal({
            title: '提示',
            content: '是否申请售后？',
            success(res) {
                if (res.confirm) {
                    request._post('/api?method=order.addAftersale', {
                        order_id: _this.data.order_id
                    },'noload').then(res => {
                        getApp().toast(res.msg)
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 1, // 回退前 delta(默认为1) 页面
                            })
                        }, 1000)
                    })
                } else if (res.cancel) { }
            }
        })
      },
    // 获取到支付方式
    emitfor_paytype(e) {
        let payment_code = e.detail
        this.setData({
            payment_code
        })
        let pay_password = wx.getStorageSync('userInfo').pay_password
        // 未设置支付密码
        if (payment_code == 'balancepay' && !pay_password) {
            wx.navigateTo({
                url: '/pages/mine/pages/my/setting-password/setting-password',
            })
            return
        }
        // 设置了支付密码
        if (payment_code == 'balancepay') {
            //余额支付
            this.setData({
                showPay: true
            })
        } else {
            // 微信支付
            this.payApi()
        }
    },
    // 验证密码成功,调支付接口
    pwdcheck_success() {
        this.setData({
            showPay: false
        })
        this.payApi()
    },
    // 余额直接不支付，关闭支付弹框
    pwdcheck_fail() {
        let _this = this
        this.setData({
            showPay: false
        })
        getApp().toast('支付失败,请重新支付')
    },
    // 支付接口api
    payApi() {
        // 支付接口
        let payment_code = this.data.payment_code
        let order_id = this.data.orderInfo.order_id
        let _this = this
        request._post('/api?method=user.pay', {
            ids: order_id,
            payment_code:'wechatpay',
            payment_type: 1
        }).then(res => {
            if (payment_code == 'balancepay') {
                //余额支付
                getApp().toast(res.msg)
                getApp().sendMessage(order_id)
                setTimeout(function () {
                    wx.navigateBack({
                        delta: 1, // 回退前 delta(默认为1) 页面
                    })
                }, 1000)
            } else {
                let obj = res.data
                wx.requestPayment({
                    timeStamp: obj.timeStamp,
                    nonceStr: obj.nonceStr,
                    package: obj.package,
                    signType: obj.signType,
                    paySign: obj.paySign,
                    signType: obj.signType,
                    success(res) {
                        getApp().toast('支付成功')
                        getApp().sendMessage(order_id)
                        wx.navigateBack({
                            delta: 1, // 回退前 delta(默认为1) 页面
                        })
                    },
                    fail(res) {
                        getApp().toast('支付失败，请重新支付')
                    }
                })

            }
        }).catch(function (res) {
            // 报错支付失败
        })
    },
    // 获取取消原因
    emitfor_cancelReason(e) {
        this.setData({
            explain: e.detail,
            isShowReason: false
        })
        this.cancelOrderApi()
    },
    // 取消订单api
    cancelOrderApi() {
        let _this = this
        let order_id = this.data.orderInfo.order_id
        request._get('/api?method=order.cancel', {
            order_id,
            explain: this.data.explain
        }).then(res => {
            getApp().toast(res.msg)

            setTimeout(function () {
                wx.navigateBack({
                    delta: 1, // 回退前 delta(默认为1) 页面
                })
            }, 1000)
        })
    },
    // 删除订单
    delOrderApi() {
        wx.showModal({
            title: '提示',
            content: '确认删除当前订单？',
            success(res) {
                if (res.confirm) {
                    request._get('/api?method=order.del', {
                        order_id: this.data.order_id
                    }).then(res => {
                        getApp().toast(res.msg)
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 1, // 回退前 delta(默认为1) 页面
                            })
                        }, 1000)
                    })
                } else if (res.cancel) { }
            }
        })
    },
    // 修改订单收货地址
    changeAdderss() {
        wx.navigateTo({
            url: '/pages/mine/pages/my/my-address/my-address?type=1',
        })
    },
    // 刷新修改的收货地址
    changeGetAdd() {
        let _this = this
        let ad_id = wx.getStorageSync('addressId')
        if (!ad_id) {
            return
        }
        request._post('/api?method=order.orderAddress', {
            order_id: this.data.order_id,
            ad_id
        }).then(res => {
            if (_this.data.timer) {
                clearInterval(_this.data.timer)
                wx.removeStorage({
                    key: 'addressId',
                })
            }
            _this.getDetail()
        })
    },
    // 提醒发货
    remindSend() {
        request._post('/api?method=order.orderRemind', {
            order_id: this.data.order_id
        }).then(res => {
            getApp().toast(res.msg)
            setTimeout(function () {
                wx.navigateBack({
                    delta: 1, // 回退前 delta(默认为1) 页面
                })
            }, 1000)
        })
    },
    // 延长收货
    lengthenOrder() {
        let _this = this
        wx.showModal({
            title: '提示',
            content: '确认延长收货？',
            success(res) {
                if (res.confirm) {
                    request._post('/api?method=order.orderCargo', {
                        order_id: _this.data.order_id
                    }).then(res => {
                        getApp().toast(res.msg)
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 1, // 回退前 delta(默认为1) 页面
                            })
                        }, 1000)
                    })
                } else if (res.cancel) { }
            }
        })

    },
    // 确认收货
    sureGetOrder() {
      let _this = this
      request._post('/api?method=order.confirm', {
          order_id: _this.data.order_id
      }).then(res => {
        console.log(res)
        if(res.extraData.transaction_id){
          let isResult = getApp().sureGetOrder(res.extraData)
          if(isResult){
            setTimeout(function () {
              wx.navigateBack({
                  delta: 1, // 回退前 delta(默认为1) 页面
              })
            }, 1000)
          }
        }else{
          getApp().toast('收货成功,可去全部订单里，查看！')
          setTimeout(function () {
            wx.navigateBack({
                delta: 1, // 回退前 delta(默认为1) 页面
            })
          }, 1000)
        }
      })
        // wx.showModal({
        //     title: '提示',
        //     content: '是否确认收货？',
        //     success(res) {
        //         if (res.confirm) {
           
        //         } else if (res.cancel) { }
        //     }
        // })
    },
    toShowMore(e) {
       
        this.setData({
            isShowNum: this.data.goods.length
        })
    },



})